package com.sdu.rpc.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

public class ServiceHandler implements Runnable {

	private Socket socket;

	public ServiceHandler(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {

		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = socket.getInputStream();
			ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
			RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();

			Method method = ServiceCache.getMethod(rpcRequest.getClassName(), rpcRequest.getMethodName(),
					rpcRequest.getParameters());

			Object service = ServiceCache.getServiceImpl(rpcRequest.getClassName());

			Object result = null;
			if (rpcRequest.getParameters() == null) {
				result = method.invoke(service);
			} else {
				result = method.invoke(service, rpcRequest.getParameters());
			}

			outputStream = socket.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(outputStream);
			oos.writeObject(result);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
